package space.jevin.jevinboot.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import space.jevin.jevinboot.entity.RequestResult;
import space.jevin.jevinboot.exception.system.ErrorCode;
import space.jevin.jevinboot.utils.json.JsonUtil;

/**
 * 返回结果统一处理
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2021/5/11 3:05 下午
 */
@RestControllerAdvice
public class ResultHandler implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        RequestResult<Object> result = new RequestResult<>();
        if (ObjectUtil.isNull(body)) {
            result.setCode(ErrorCode.SUCCESS);
            return result;
        }
        // 判断是ResponseData子类或其本身就返回Object o本身，因为有可能是接口返回时创建了ResponseData,这里避免再次封装
        if (body instanceof RequestResult) {
            return body;
        }
        // String特殊处理，否则会抛异常
        if (body instanceof String) {
            result.setData(body);
            result.setCode(ErrorCode.SUCCESS);
            String resultBody = JsonUtil.writeValueAsString(result);
            if (StrUtil.isNotBlank(resultBody)) {
                return resultBody;
            }
            return body;
        }
        result.setData(body);
        result.setCode(ErrorCode.SUCCESS);
        return result;
    }
}
